// app/controller/logs.js
const {
  Controller
} = require('egg');

class LogsController extends Controller {
  async getLogs() {
    const {
      ctx
    } = this;
    // 获取请求参数，设置默认值
    const {
      page = 1, page_size = 10, user_name
    } = ctx.request.body;

    try {
      // 构建 SQL 查询语句
      let sql = 'SELECT * FROM api_logs';
      const values = [];

      if (user_name) {
        sql += ' WHERE JSON_EXTRACT(user_info, \'$.name\') = ?';
        values.push(user_name);
      }

      // 添加按时间倒序排序
      sql += ' ORDER BY created_at DESC';

      // 计算偏移量
      const offset = (page - 1) * page_size;
      sql += ' LIMIT ? OFFSET ?';
      values.push(Number(page_size), offset);

      // 执行 SQL 查询
      const logs = await ctx.app.mysql.query(sql, values);

      // 获取总记录数
      let countSql = 'SELECT COUNT(*) as total FROM api_logs';
      const countValues = [];
      if (user_name) {
        countSql += ' WHERE JSON_EXTRACT(user_info, \'$.name\') = ?';
        countValues.push(user_name);
      }
      const countResult = await ctx.app.mysql.query(countSql, countValues);
      const total = countResult[0].total;

      // 计算总页数
      const totalPages = Math.ceil(total / page_size);

      ctx.body = {
        logs,
        page,
        page_size,
        total,
        totalPages
      };
    } catch (error) {
      ctx.logger.error('Error getting logs:', error);
      ctx.body = {
        success: false,
        message: 'Failed to get logs'
      };
    }
  }
}

module.exports = LogsController;